/**
 * @Project : ProgrammingExercises
 * @Package : Leetcode
 * @File : Q2516.java
 * @Author : WangRuoyu
 * @Date 2023/1/16 17:25
 */

package leetcode;


// TODO
public class Q2516 {
    public int takeCharacters(String s, int k) {
        if (k == 0) {
            return 0;
        } else if ((k * 3) > s.length()) {
            return -1;
        } else {
            int[] index = {0, 0, 0};
            for (int i = 0; i < s.length(); i++) {
                index[s.charAt(i) - 'a']++;
            }
            index[0] -= k;
            index[1] -= k;
            index[2] -= k;

            if ((index[0] == 0) && (index[1] == 0) && (index[2] == 0)) {
                return s.length();
            } else if ((index[0] < 0) || (index[1] < 0) || (index[2] < 0)) {
                return -1;
            } else {
                for (int i = s.length() - 3 * k; i > 0; i--) {
                    for (int j = 0; j <= s.length() - i; j++) {
                        int[] index2 = {index[0], index[1], index[2]};
                        for (int l = j; l < j + i; l++) {
                            index2[s.charAt(l) - 'a']--;
                        }
                        if ((index2[0] >= 0) && (index2[1] >= 0) && (index2[2] >= 0)) {
                            return s.length() - i;
                        }
                    }
                }
                return -1;
            }
        }
    }

    public static void main(String[] args) {
        Q2516 sl = new Q2516();
        String s = "aabaaaacaabc";
        int k = 2;
        System.out.println(sl.takeCharacters(s, k));
    }
}